from flask import Flask, render_template, request, jsonify
import requests
from pyecharts import options as opts
from pyecharts.charts import Pie

app = Flask(__name__)

name_describe_dict = {
    'HeWeather5': '和风标识', 'suggestion': '生活指数', 'drsg': '穿衣指数', 'txt': '数据详情', 'brf': '生活指数简介',
    'uv': '紫外线指数', 'comf': '舒适度指数', 'flu': '感冒指数', 'sport': '运动指数', 'trav': '旅游指数', 'cw': '洗车指数',
    'status': '状态码', 'hourly_forecast': '每小时预报', 'tmp': '温度', 'pop': '降水概率', 'pres': '大气压',
    'wind': '风力情况', 'deg': '风向（360度）', 'sc': '风力等级', 'spd': '风速', 'dir': '风向', 'hum': '相对湿度',
    'date': '日期', 'cond': '天气状况', 'code': '天气状况代码', 'now': '实况天气', 'fl': '感冒指数', 'pcpn': '降水量',
    'vis': '能见度', 'aqi': 'AQI', 'city': '城市名', 'pm25': 'PM2.5', 'pm10': 'PM10', 'co': 'CO',
    'so2': 'SO2', 'no2': 'NO2', 'qlty': '空气质量', 'o3': 'O3', 'basic': '基本信息', 'id': '城市ID',
    'cnty': '国家', 'lat': '纬度', 'update': '更新时间', 'loc': '当地时间', 'utc': 'UTC时间', 'lon': '经度',
    'daily_forecast': '天气预报', 'txt_d': '白天天气状况描述', 'txt_n': '夜间天气状况描述', 'code_d': '白天天气状况代码',
    'code_n': '夜间天气状况代码', 'astro': '天文指数', 'ms': '月落时间', 'ss': '日落时间', 'sr': '日出时间', 'mr': '月升时间',
    'max': '最高温度', 'min': '最低温度'}


@app.route('/')
def index():
    cities_str = request.args.get('cities')
    print(cities_str)
    if not cities_str:
        return render_template('index.html')
    cities_list = cities_str.split('/')
    return render_template(
        'index.html',
        cities_list=cities_list,
        cities_str=cities_str
    )


@app.route('/describe')
def describe():
    return render_template(
        'describe.html',
        name_describe_dict=name_describe_dict
    )


@app.route('/api_data')
def api_data():
    """
    获取数据的Url:
    https://way.jd.com/he/freeweather?city=beijing&appkey=aebd7367d3b34f00e0b4362d20a22ffd
    """
    city = request.args.get('city')
    url = f'https://way.jd.com/he/freeweather?city={city.strip()}&appkey=aebd7367d3b34f00e0b4362d20a22ffd'
    response = requests.get(url)
    return response.json()


def get_pie(value):
    value = int(value)
    c = (
        Pie()
            .add("", [["", value], ["", max(300 - value, 0)]],
                 radius=["80%", "90%"],
                 label_opts=opts.LabelOpts(is_show=False))
            .set_colors(["#4f7553", "#888"])
            .set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=False)
        )
    )
    return c


@app.route('/detail')
def detail():
    city = request.args.get('city')
    url = f'https://way.jd.com/he/freeweather?city={city.strip()}&appkey=aebd7367d3b34f00e0b4362d20a22ffd'
    response = requests.get(url)
    data = response.json()
    weather = data['result']['HeWeather5'][0]
    if weather['status'] == "unknown location":
        return '输入城市错误, 请重新输入'
    elif weather['status'] == 'ok':
        return render_template(
            'detail.html',
            weather=weather,
            pie=get_pie(weather['aqi']['city']['aqi']).dump_options()
        )
    else:
        return "未知错误"


if __name__ == '__main__':
    app.run()
